#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>
#include <signal.h>

int message = 1;
//pthread_mutex_t mutex = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex;
sem_t sem;

void  my_thread_exit(void *arg)
{
    printf("thread name:%s>>> thread is exit!\n", (char *)arg);
}

void thread_exit(int sig)
{
    if(sig == SIGINT)
    {
        pthread_mutex_destroy(&mutex);
        sem_destroy(&sem);
        exit(1);
    }
}

void *thread1(void *arg)
{
    int fd = *((int *)arg);
    //lock:
    //上锁的注意事项：锁的代码颗粒度小:只锁访问共享资源的代码段
    //lock/unlock:不要忘记解锁
    while(1)
    {   
        //pthread_mutex_lock(&mutex); //
        sem_wait(&sem);
        // if()
        // {
        //     pthread_mutex_unlock(&mutex);
        //     return 0;
        // }
        write(fd, "hello", 5);
        write(fd, "world", 5);
        write(fd, "\n", 1);
        //pthread_mutex_unlock(&mutex);
        sem_post(&sem);
        
    }
    //unlock
}

void *thread2(void *arg)
{   
    int fd = *((int *)arg);

    while(1)
    {
        //pthread_mutex_lock(&mutex);
        sem_wait(&sem);
        // while(pthread_mutex_trylock(&mutex) == EBUSY)
        // {
        //     printf("mutex is lock!\n");
        //     continue;
        // }
        write(fd, "hhhhh", 5);
        write(fd, "wwwww", 5);
        write(fd, "\n", 1);
        //pthread_mutex_unlock(&mutex);
        sem_post(&sem);
    }
}

struct Message
{
   int action;
   char msg[100];
};

int main(int argc, char **argv)
{
    int ret;
    pthread_t id1;
    pthread_t id2;
    int num = 5;
    int count = 6;
    char *ptr = "hello world";
    struct Message msg;

    signal(SIGINT, thread_exit);

    
    pthread_mutex_init(&mutex, NULL);
    sem_init(&sem, 0, 1);

    int fd = open("a.txt", O_CREAT | O_RDWR | O_TRUNC, 0655);
    if(fd == -1)
    {
        perror("open file error!");
        exit(1);
    }

    ret = pthread_create(&id1, NULL, thread1, (void *)&fd);  //传递地址
    if(ret < 0)
    {
        perror("thread1 create error!");
        exit(1);
    }
    ret = pthread_create(&id2, NULL, thread2, (void *)&fd); //传值
    if(ret < 0)
    {
        perror("thread2 create error!");
        exit(1);
    }
    
    //缺点：阻塞--线程资源不能被立即回收
    pthread_join(id1, NULL); //阻塞等待此线程退出，并且回收资源
    //void *result;
    pthread_join(id2, NULL);
    //printf("result = %s\n", (char *)(result));
    
    //线程：分离态  线程退出系统自动回收线程的资源
    //pthread_detach(id1);
    //pthread_detach(id2);

    printf("id1 = %ld\n", id1);
    printf("id2 = %ld\n", id2);

    printf("num = %d\n", num);

    pause();

    return 0;
}